<template>
  <div class="regional-sales-analysis">
    <!-- 页面标题和筛选器 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">区域销售分析</h1>
        <div class="filter-controls">
          <a-select v-model="regionLevel" style="width: 120px; margin-right: 12px" @change="onRegionLevelChange">
            <a-select-option value="province">省份</a-select-option>
            <a-select-option value="city">城市</a-select-option>
            <a-select-option value="area">区县</a-select-option>
          </a-select>
          <a-range-picker
            v-model="dateRange"
            format="YYYY-MM-DD"
            :placeholder="['开始日期', '结束日期']"
            @change="onDateRangeChange"
            style="width: 240px; margin-right: 12px"
          />
          <a-button type="primary" @click="refreshData" :loading="loading"> <a-icon type="reload" />刷新数据 </a-button>
        </div>
      </div>
    </div>

    <!-- 概览统计卡片 -->
    <div class="overview-section">
      <div class="overview-grid">
        <div class="overview-card">
          <div class="card-content">
            <div class="card-header">
              <span class="card-title">覆盖区域数</span>
              <a-tooltip title="有销售记录的区域总数">
                <a-icon type="question-circle" class="help-icon" />
              </a-tooltip>
            </div>
            <div class="card-value">{{ formatNumber(overview.totalRegions) }}</div>
            <div class="card-trend" :class="getTrendClass(overview.regionsGrowthRate)">
              <a-icon :type="getTrendIcon(overview.regionsGrowthRate)" />
              {{ overview.regionsGrowthRate }}%
              <span class="trend-label">较去年同期</span>
            </div>
          </div>
        </div>

        <div class="overview-card">
          <div class="card-content">
            <div class="card-header">
              <span class="card-title">总销售额</span>
              <a-tooltip title="所有区域的销售总金额">
                <a-icon type="question-circle" class="help-icon" />
              </a-tooltip>
            </div>
            <div class="card-value">{{ formatCurrency(overview.totalSales) }}</div>
            <div class="card-trend" :class="getTrendClass(overview.salesGrowthRate)">
              <a-icon :type="getTrendIcon(overview.salesGrowthRate)" />
              {{ overview.salesGrowthRate }}%
              <span class="trend-label">较去年同期</span>
            </div>
          </div>
        </div>

        <div class="overview-card">
          <div class="card-content">
            <div class="card-header">
              <span class="card-title">平均区域销售额</span>
              <a-tooltip title="每个区域的平均销售金额">
                <a-icon type="question-circle" class="help-icon" />
              </a-tooltip>
            </div>
            <div class="card-value">{{ formatCurrency(overview.avgRegionSales) }}</div>
            <div class="card-trend" :class="getTrendClass(overview.avgGrowthRate)">
              <a-icon :type="getTrendIcon(overview.avgGrowthRate)" />
              {{ overview.avgGrowthRate }}%
              <span class="trend-label">较去年同期</span>
            </div>
          </div>
        </div>

        <div class="overview-card">
          <div class="card-content">
            <div class="card-header">
              <span class="card-title">最高区域占比</span>
              <a-tooltip title="销售额最高区域占总销售额的比例">
                <a-icon type="question-circle" class="help-icon" />
              </a-tooltip>
            </div>
            <div class="card-value">{{ overview.topRegionRatio }}%</div>
            <div class="card-trend" :class="getTrendClass(overview.ratioGrowthRate)">
              <a-icon :type="getTrendIcon(overview.ratioGrowthRate)" />
              {{ overview.ratioGrowthRate }}%
              <span class="trend-label">较去年同期</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表分析区域 -->
    <div class="charts-section">
      <div class="charts-grid">
        <!-- 区域销售分布 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3 class="chart-title">区域销售分布</h3>
            <div class="chart-controls">
              <a-radio-group v-model="mapDataType" size="small" @change="updateMapChart">
                <a-radio-button value="sales">销售额</a-radio-button>
                <a-radio-button value="orders">订单数</a-radio-button>
                <a-radio-button value="customers">客户数</a-radio-button>
              </a-radio-group>
            </div>
          </div>
          <div class="chart-content">
            <div ref="mapChart" class="chart-container"></div>
          </div>
        </div>

        <!-- 区域销售趋势 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3 class="chart-title">区域销售趋势</h3>
            <div class="chart-controls">
              <a-select v-model="trendPeriod" size="small" style="width: 100px" @change="updateTrendChart">
                <a-select-option value="month">月度</a-select-option>
                <a-select-option value="quarter">季度</a-select-option>
                <a-select-option value="year">年度</a-select-option>
              </a-select>
            </div>
          </div>
          <div class="chart-content">
            <div ref="trendChart" class="chart-container"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import moment from 'moment'
import { getRegionOverview, getRegionDistribution, getRegionTrend } from '@/api/oms/statistics'

export default {
  name: 'RegionalSalesAnalysis',
  data() {
    return {
      loading: false,
      dateRange: [],
      regionLevel: 'province',
      mapDataType: 'sales',
      trendPeriod: 'month',
      resizeTimer: null,

      overview: {
        totalRegions: 0,
        totalSales: 0,
        avgRegionSales: 0,
        topRegionRatio: 0,
        regionsGrowthRate: 0,
        salesGrowthRate: 0,
        avgGrowthRate: 0,
        ratioGrowthRate: 0,
      },

      mapData: [],
      trendData: [],
      charts: {},
    }
  },

  mounted() {
    this.initDateRange()
    this.loadData()
    this.initCharts()
    window.addEventListener('resize', this.handleResize)
  },

  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    Object.values(this.charts).forEach((chart) => {
      if (chart) chart.dispose()
    })
  },

  methods: {
    initDateRange() {
      const endDate = moment()
      const startDate = moment().subtract(30, 'days')
      this.dateRange = [startDate, endDate]
    },

    onRegionLevelChange(value) {
      this.regionLevel = value
      this.loadData()
    },

    onDateRangeChange(dates) {
      this.dateRange = dates
      if (dates && dates.length === 2) {
        this.loadData()
      }
    },

    refreshData() {
      this.loadData()
    },

    async loadData() {
      this.loading = true
      try {
        await this.loadRealData()
        this.updateCharts()
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },

    async loadRealData() {
      const startDate = this.dateRange[0] ? this.dateRange[0].format('YYYY-MM-DD') : null
      const endDate = this.dateRange[1] ? this.dateRange[1].format('YYYY-MM-DD') : null

      // 并行加载所有数据
      const [overviewRes, distributionRes, trendRes] = await Promise.all([
        getRegionOverview(startDate, endDate, this.regionLevel),
        getRegionDistribution(startDate, endDate, this.regionLevel, this.mapDataType),
        getRegionTrend(this.trendPeriod, this.regionLevel, 12),
      ])

      // 处理概览数据
      if (overviewRes.success && overviewRes.result) {
        this.overview = {
          totalRegions: overviewRes.result.totalRegions || 0,
          totalSales: overviewRes.result.totalSales || 0,
          avgRegionSales: overviewRes.result.avgRegionSales || 0,
          topRegionRatio: overviewRes.result.topRegionRatio || 0,
          regionsGrowthRate: overviewRes.result.regionsGrowthRate || 0,
          salesGrowthRate: overviewRes.result.salesGrowthRate || 0,
          avgGrowthRate: overviewRes.result.avgGrowthRate || 0,
          ratioGrowthRate: overviewRes.result.ratioGrowthRate || 0,
        }
      }

      // 处理分布数据
      if (distributionRes.success && distributionRes.result) {
        this.mapData = distributionRes.result.map((item) => ({
          name: item.regionName || item.name,
          value: item.value || item.sales || 0,
          code: item.regionCode || item.code,
        }))
      }

      // 处理趋势数据
      if (trendRes.success && trendRes.result) {
        this.trendData = trendRes.result.map((item) => ({
          period: item.period,
          totalSales: item.totalSales || item.sales || 0,
          orderCount: item.orderCount || item.orders || 0,
        }))
      }
    },

    updateCharts() {
      this.$nextTick(() => {
        this.updateMapChartDisplay()
        this.updateTrendChartDisplay()
      })
    },

    initCharts() {
      this.$nextTick(() => {
        this.charts.mapChart = echarts.init(this.$refs.mapChart)
        this.charts.trendChart = echarts.init(this.$refs.trendChart)
      })
    },

    async updateMapChart() {
      // 重新加载分布数据
      const startDate = this.dateRange[0] ? this.dateRange[0].format('YYYY-MM-DD') : null
      const endDate = this.dateRange[1] ? this.dateRange[1].format('YYYY-MM-DD') : null
      try {
        const distributionRes = await getRegionDistribution(startDate, endDate, this.regionLevel, this.mapDataType)
        if (distributionRes.success && distributionRes.result) {
          this.mapData = distributionRes.result.map((item) => ({
            name: item.regionName || item.name,
            value: item.value || item.sales || 0,
            code: item.regionCode || item.code,
          }))
          this.updateMapChartDisplay()
        }
      } catch (error) {
        console.error('更新地图数据失败:', error)
      }
    },

    updateMapChartDisplay() {
      if (!this.charts.mapChart) return

      const dataTypeMap = {
        sales: { title: '销售额', unit: '¥', formatter: (value) => `¥${this.formatNumber(value)}` },
        orders: { title: '订单数', unit: '', formatter: (value) => `${value}单` },
        customers: { title: '客户数', unit: '', formatter: (value) => `${value}个` },
      }
      const currentType = dataTypeMap[this.mapDataType] || dataTypeMap.sales

      const option = {
        title: { text: `区域${currentType.title}分布`, left: 'center' },
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const data = params[0]
            return `${data.name}<br/>${currentType.title}: ${currentType.formatter(data.value)}`
          },
        },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: {
          type: 'category',
          data: this.mapData.map((item) => item.name),
        },
        yAxis: {
          type: 'value',
          axisLabel: { formatter: currentType.formatter },
        },
        series: [
          {
            type: 'bar',
            data: this.mapData.map((item) => item.value),
            itemStyle: { color: '#188df0' },
          },
        ],
      }

      this.charts.mapChart.setOption(option)
    },

    async updateTrendChart() {
      // 重新加载趋势数据
      try {
        const trendRes = await getRegionTrend(this.trendPeriod, this.regionLevel, 12)
        if (trendRes.success && trendRes.result) {
          this.trendData = trendRes.result.map((item) => ({
            period: item.period,
            totalSales: item.totalSales || item.sales || 0,
            orderCount: item.orderCount || item.orders || 0,
          }))
          this.updateTrendChartDisplay()
        }
      } catch (error) {
        console.error('更新趋势数据失败:', error)
      }
    },

    updateTrendChartDisplay() {
      if (!this.charts.trendChart) return

      const option = {
        title: { text: '区域销售趋势', left: 'center' },
        tooltip: { trigger: 'axis' },
        legend: { data: ['销售额', '订单数'], bottom: 0 },
        grid: { left: '3%', right: '4%', bottom: '15%', top: '15%', containLabel: true },
        xAxis: {
          type: 'category',
          data: this.trendData.map((item) => item.period),
        },
        yAxis: [
          {
            type: 'value',
            name: '销售额(元)',
            position: 'left',
            axisLabel: { formatter: (value) => `¥${this.formatNumber(value)}` },
          },
          {
            type: 'value',
            name: '订单数',
            position: 'right',
            axisLabel: { formatter: '{value}' },
          },
        ],
        series: [
          {
            name: '销售额',
            type: 'line',
            yAxisIndex: 0,
            data: this.trendData.map((item) => item.totalSales),
            smooth: true,
            itemStyle: { color: '#5470c6' },
            areaStyle: { opacity: 0.3 },
          },
          {
            name: '订单数',
            type: 'line',
            yAxisIndex: 1,
            data: this.trendData.map((item) => item.orderCount),
            smooth: true,
            itemStyle: { color: '#91cc75' },
          },
        ],
      }

      this.charts.trendChart.setOption(option)
    },

    handleResize() {
      if (this.resizeTimer) clearTimeout(this.resizeTimer)
      this.resizeTimer = setTimeout(() => {
        Object.values(this.charts).forEach((chart) => {
          if (chart) chart.resize()
        })
      }, 100)
    },

    formatCurrency(value) {
      if (!value) return '¥0'
      return `¥${this.formatNumber(value)}`
    },

    formatNumber(value) {
      if (!value) return '0'
      return Number(value).toLocaleString()
    },

    getTrendClass(rate) {
      const numRate = Number(rate)
      if (numRate > 0) return 'trend-up'
      if (numRate < 0) return 'trend-down'
      return 'trend-flat'
    },

    getTrendIcon(rate) {
      const numRate = Number(rate)
      if (numRate > 0) return 'arrow-up'
      if (numRate < 0) return 'arrow-down'
      return 'minus'
    },
  },
}
</script>

<style lang="less" scoped>
.regional-sales-analysis {
  background: #f5f7fa;
  min-height: 100vh;
  padding: 24px;
  max-width: 1600px;
  margin: 0 auto;

  @media (max-width: 1200px) {
    max-width: 100%;
    padding: 16px;
  }

  @media (max-width: 768px) {
    padding: 12px;
  }
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 24px 32px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.15);

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 16px;

    @media (max-width: 768px) {
      flex-direction: column;
      align-items: stretch;
    }

    .page-title {
      font-size: 28px;
      font-weight: 600;
      color: #ffffff;
      margin: 0;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

      @media (max-width: 768px) {
        font-size: 24px;
        text-align: center;
      }
    }

    .filter-controls {
      display: flex;
      align-items: center;
      gap: 12px;
      flex-wrap: wrap;

      @media (max-width: 768px) {
        justify-content: center;
      }

      .ant-btn-primary {
        background: rgba(255, 255, 255, 0.2);
        border: 1px solid rgba(255, 255, 255, 0.3);
        border-radius: 8px;
        font-weight: 500;
        backdrop-filter: blur(10px);
        transition: all 0.3s ease;

        &:hover {
          background: rgba(255, 255, 255, 0.3);
          border-color: rgba(255, 255, 255, 0.5);
          transform: translateY(-1px);
        }
      }
    }
  }
}

.overview-section {
  margin-bottom: 24px;

  .overview-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;

    @media (max-width: 1200px) {
      grid-template-columns: repeat(2, 1fr);
    }

    @media (max-width: 768px) {
      grid-template-columns: 1fr;
      gap: 12px;
    }
  }

  .overview-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    min-height: 140px;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    }

    .card-content {
      padding: 24px;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      @media (max-width: 768px) {
        padding: 20px;
      }

      .card-header {
        display: flex;
        align-items: center;
        margin-bottom: 16px;

        .card-title {
          font-size: 14px;
          color: #909399;
          font-weight: 500;
        }

        .help-icon {
          margin-left: 8px;
          color: #c0c4cc;
          cursor: help;
        }
      }

      .card-value {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 12px;
        word-break: break-all;

        @media (max-width: 768px) {
          font-size: 22px;
        }
      }

      .card-trend {
        font-size: 12px;
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        .trend-label {
          margin-left: 4px;
          color: #909399;
        }

        &.trend-up {
          color: #67c23a;
        }

        &.trend-down {
          color: #f56c6c;
        }

        &.trend-flat {
          color: #909399;
        }
      }
    }
  }
}

.charts-section {
  .charts-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    margin-bottom: 16px;

    @media (max-width: 768px) {
      grid-template-columns: 1fr;
      gap: 12px;
    }
  }

  .chart-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .chart-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20px 24px 0;

      @media (max-width: 768px) {
        padding: 16px 20px 0;
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
      }

      .chart-title {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #303133;

        @media (max-width: 768px) {
          font-size: 15px;
        }
      }

      .help-icon {
        margin-left: 8px;
        color: #c0c4cc;
        cursor: help;
      }

      .chart-controls {
        display: flex;
        align-items: center;
        gap: 8px;
      }
    }

    .chart-content {
      padding: 16px 24px 24px;

      @media (max-width: 768px) {
        padding: 12px 20px 20px;
      }

      .chart-container {
        width: 100%;
        height: 350px;

        @media (max-width: 768px) {
          height: 280px;
        }

        > div {
          width: 100% !important;
          height: 100% !important;
        }
      }
    }
  }
}
</style>
